<template>
  <div class="schedule" :style="borderStyle">
    <el-calendar
      v-model="value"
      :range="[weekCheckingIn(), weekCheckingIn1()]"
      :style="borderStyle"
    >
      <template slot="dateCell" slot-scope="data">
        <div :class="data.isSelected ? 'is-selected' : ''">
          <p>
            <!--这里原本有动态绑定的class@click=""，去掉-->
            {{
              data.data.day
                .split("-")
                .slice(2)
                .join("")
            }}
            <span class="count" @click="queryAllSchedulesByDate(data.data.day)">
              {{
                dealMyDate(data.data.day) !== undefined &&
                  dealMyDate(data.data.day) !== null &&
                  dealMyDate(data.data.day).length > 0
                  ? "共" + dealMyDate(data.data.day).length + "项"
                  : ""
              }}
            </span>
            <br>
            <span
              v-if="
                dealMyDate(data.data.day) !== undefined &&
                  dealMyDate(data.data.day) !== null &&
                  dealMyDate(data.data.day).length > 0
              "
            >
              <span
                v-for="it in dealMyDate(data.data.day).slice(0, 4)"
                :key="it.id"
                class="sch_title"
                :class="
                  it.rcjb == '3'
                    ? 'is-danger'
                    : it.rcjb == '1'
                      ? 'is-common'
                      : 'is-important'
                "
                @click="calItem(it.id, data.data.day)"
              >
                {{ it.title }}
                <br>
              </span>
            </span>
          </p>
        </div>
        <el-dialog :visible.sync="dialogVisible" :close-on-click-modal="false">
          <el-form ref="form" :model="form" label-width="100px">
            <el-form-item label="日程标题" prop="title">
              <el-input v-model="form.title" disabled />
            </el-form-item>

            <el-form-item label="日期">
              <el-col :span="11">
                <el-form-item prop="kssj">
                  <el-date-picker
                    v-model="form.kssj"
                    type="datetime"
                    placeholder="开始时间"
                    style="width: 100%"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col class="line" :span="2">-</el-col>
              <el-col :span="11">
                <el-form-item
                  prop="jssj"
                ><el-date-picker
                  v-model="form.jssj"
                  type="datetime"
                  placeholder="结束时间"
                  style="width: 100%"
                  disabled
                /></el-form-item>
              </el-col>
            </el-form-item>
            <el-form-item label="是否公开" prop="sfgk">
              <el-switch v-model="form.sfgk" disabled />
            </el-form-item>
            <el-form-item label="日程级别" prop="rcjb">
              <el-radio-group v-model="form.rcjb" disabled>
                <el-radio label="1">一般日程</el-radio>
                <el-radio label="2">重要日程</el-radio>
                <el-radio label="3">紧急日程</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="日程描述" prop="content">
              <el-input v-model="form.content" type="textarea" disabled />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">关闭</el-button>
          </div>
        </el-dialog>
      </template>
    </el-calendar>
  </div>
</template>

<script>
import { queryAllScheduleByPage } from '@/api/schedule/schedule';
export default {
  name: 'ScheduleDisplay',
  props: {
    temp: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      value: new Date(),
      resDate: [],
      dialogVisible: false,
      map: {},
      MondayTime: '',
      form: {
        fqr: '',
        title: '',
        kssj: '',
        jssj: '',
        sfgk: true,
        rcjb: '',
        content: ''
      },
      resultTime: [],
      borderStyle: {}
    };
  },
  computed: {
    themes() {
      return this.$store.getters.theme;
    }
  },
  watch: {
    themes: {
      handler(val, oldVal) {
        console.log(val);
        this.borderStyle.borderRadius = val.bkdx;
        this.borderStyle.border = '1px solid ' + val.bkys;
        this.borderStyle.boxShadow = '0 2px 4px rgba(0, 0, 0, .12)';
        this.borderStyle.background = val.columnGroundColor;
        this.borderStyle.color = val.fontColor;
        this.borderStyle = Object.assign({}, this.borderStyle);
      },
      immediate: true, // 父组件第一次传值时，执行handler，false则第一次不执行
      deep: false // formType为对象时，设置为true，此属性监听对象发生变化
    }
  },
  mounted() {
    window.addEventListener(
      'storage',
      e => {
        // e只是一个传参
        // 获取被修改的键值
        if (e.key == 'themes') {
          // 分别打印会发现内容一致
          // console.log(e.storageArea.themes);
          console.log(localStorage.themes);
          this.$store
            .dispatch('GetThemes')
            .then(res => {
              return true;
            })
            .catch(error => {
              console.log(error);
            });
          // this.$store.getters.theme = JSON.parse(localStorage.themes);
        }
      },
      false
    );
  },
  created() {
    this.initData();
  },
  methods: {
    weekCheckingIn() {
      var now = new Date();
      var nowTime = now.getTime();
      var day = now.getDay() || 7; // 不加 || 7.周末会变成下周一
      var oneDayTime = 24 * 60 * 60 * 1000;
      var MondayTime = nowTime - (day - 1) * oneDayTime; // 显示周一
      // var SundayTime = nowTime + (7 - day) * oneDayTime; //显示周日
      // 调用方法
      return MondayTime;
    },
    weekCheckingIn1() {
      var now = new Date();
      var nowTime = now.getTime();
      var day = now.getDay() || 7; // 不加 || 7.周末会变成下周一
      var oneDayTime = 24 * 60 * 60 * 1000;
      // var MondayTime = nowTime - (day - 1) * oneDayTime; //显示周一
      var SundayTime = nowTime + (14 - day) * oneDayTime; // 显示周日
      // 调用方法
      return SundayTime;
    },
    getCurrentWeekMondayDate() {
      var now1 = new Date();
      var nowTime1 = now1.getTime();
      var day1 = now1.getDay() || 7; // 不加 || 7.周末会变成下周一
      var oneDayTime1 = 24 * 60 * 60 * 1000;
      var MondayTime1 = nowTime1 - (day1 - 1) * oneDayTime1; // 显示周一
      // console.log(MondayTime1);
      var currentWeekMondayTime = new Date(MondayTime1);
      var year = currentWeekMondayTime.getFullYear();
      var month = currentWeekMondayTime.getMonth() + 1;
      var day = currentWeekMondayTime.getDate();
      var HH = currentWeekMondayTime.getHours();
      var mm = currentWeekMondayTime.getMinutes();
      mm = mm > 9 ? mm : '0' + mm.toString();
      var ss = currentWeekMondayTime.getSeconds();
      return `${year}-${month}-${day} ${HH}:${mm}:${ss}`;
    },
    // 获取近期的日程数据
    initData() {
      // console.info(this.$store.getters.user.username);
      var userid = this.$store.getters.user.username;
      var d = this.getCurrentWeekMondayDate();
      console.log(d);
      this.resDate = [];
      this.map = [];
      // 分页获取日程信息
      queryAllScheduleByPage({
        page: 0,
        size: 100,
        datetime: d,
        state: '1'
      }).then(res => {
        var result = res.content;
        console.log(result + '=====');
        var code = res.state;
        console.log(code + '=====');
        if (code == 200) {
          this.rcdata = [];
          result.forEach(item => {
            var kssj = item.kssj.substring(0, 10);
            var jssj = item.jssj.substring(0, 10);

            if (typeof kssj === 'string') {
              const reg = /^\d{4}-(0?[1-9]|1[0-2])-((0?[1-9])|((1|2)[0-9])|30|31)$/g;
              if (!reg.test(kssj)) throw `开始时间：${kssj}时间格式错误`;
            }
            if (typeof jssj === 'string') {
              const reg = /^\d{4}-(0?[1-9]|1[0-2])-((0?[1-9])|((1|2)[0-9])|30|31)$/g;
              if (!reg.test(jssj)) throw `结束时间：${jssj}时间格式错误`;
            }
            let start = new Date(kssj);
            const end = new Date(jssj);
            const resultTime = [];
            // 当 开始时间小于结束时间的时候进入循环
            while (start <= end) {
              const getDay = start.getDate();
              // 月份需要加 1
              const getMonth = start.getMonth() + 1;
              const getYear = start.getFullYear();
              /**
               * 拼接时间格式
               * (getMonth >= 10 ? `${getMonth}` : `0${getMonth}`) 自动给 小于10的时间前面补0
               */
              const setTime =
                `${getYear}-` +
                (getMonth >= 10 ? `${getMonth}` : `0${getMonth}`) +
                '-' +
                (getDay >= 10 ? `${getDay}` : `0${getDay}`);

              resultTime.push(setTime);
              /**
               * 重新设置开始时间
               * 使用 setFullYear() 方法会自动将时间累加，返回的是时间戳格式
               * 使用 new Date() 将时间重新设置为标准时间
               * getMonth - 1 将月份时间重新还原
               */
              start = new Date(
                start.setFullYear(getYear, getMonth - 1, getDay + 1)
              );

              // this.rcdata.push(this.resDate);
            }
            resultTime.forEach(e => {
              var sch = {
                // id: result.data[i].id,
                date: e,
                id: item.id,
                title: item.title,
                rcjb: item.rcjb,
                content: item.content,
                kssj: item.kssj,
                jssj: item.jssj,
                sfgk: item.sfgk
              };
              this.resDate.push(sch);
            });
          });

          var arr = this.resDate;
          // 遍历数组，考虑如果日期相同 就把相同日期的日程内容和日程级别组装在一起，装在数组里面，

          // const mapping = {};
          // this.map = {};
          arr.forEach(element => {
            if (!this.map[element.date]) {
              this.map[element.date] = [];
            }
            this.map[element.date].push(element);
          });

          this.map = { ...this.map };
        }
        // console.log(this.map);
      });
    },

    // 日程展示
    dealMyDate(v) {
      // let res = [];
      if (this.map[v]) {
        return this.map[v];
      }
    },
    calItem(scheduleId, d) {
      console.log('点击的日期是：', d);

      this.resDate = this.dealMyDate(d);
      this.resDate.forEach(e => {
        if (e.id == scheduleId) {
          this.form = e;
          console.log('form是：', this.form, e.index);
        }
      });
      this.dialogVisible = true;
    },

    // 格式化日期：yyyy-MM-dd
    formatDate(date) {
      var myyear = date.getFullYear();
      var mymonth = date.getMonth() + 1;
      var myweekday = date.getDate();

      if (mymonth < 10) {
        mymonth = '0' + mymonth;
      }
      if (myweekday < 10) {
        myweekday = '0' + myweekday;
      }
      return myyear + '-' + mymonth + '-' + myweekday;
    },
    queryAllSchedulesByDate(queryday) {
      this.$emit('queryCalendarSchedule', queryday);
    }
  }
};
</script>
<style scoped>
.sch_title {
  overflow: hidden;
  display: -webkit-box;
  text-overflow: ellipsis;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  white-space: normal;
}
.schedule ::v-deep .el-table .cell {
  white-space: pre-line;
  text-align: center;
}

.schedule ::v-deep .el-calendar-table .el-calendar-day:hover {
  background-color: #9ba9a8;
}

.schedule ::v-deep .el-calendar-table td.is-today {
  color: rgb(61, 73, 87);
  background: #9ba9a8;
}

.schedule ::v-deep .el-input__prefix {
  display: none;
}
.schedule ::v-deep .el-input--prefix .el-input__inner {
  padding-left: 15px;
  padding-right: 15px;
}
.line {
  text-align: center;
}
.schedule {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
  box-sizing: border-box;
  border-radius: 5px;
}
.schedule ::v-deep .el-calendar-day {
  height: 128px;
}

.schedule ::v-deep .el-calendar__body {
  padding: 0px 0px 0px;
}
.schedule ::v-deep .el-calendar-table thead th {
  border: 1px solid #ebeef5;
  background-color: #f4f4f4;
}
.schedule ::v-deep .el-calendar__header {
  display: none;
}
.is-selected {
  /* color: #f8a535; */
  font-size: 10px;
  margin-top: 5px;
}
.is-danger {
  color: #ff5722;
}
.is-important {
  color: #ffb800;
}
.is-common {
  color: #5fb878;
}
.count {
  float: right;
  font-size: small;
  color: rgb(11, 111, 219);
}

.schedule ::v-deep .el-input.is-disabled .el-input__inner {
  color: #000;
}

.schedule ::v-deep .el-textarea.is-disabled .el-textarea__inner {
  color: #000;
}
.schedule ::v-deep .el-switch .el-switch__core {
  border-color: #000;
  background-color: #000;
}
.schedule ::v-deep .el-radio__input.is-disabled.is-checked .el-radio__inner {
  background-color: #000;
  border-color: #000;
}
</style>
